package com.taotao.admin.rest;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.admin.pojo.TableUI;
import com.taotao.admin.pojo.WechatRequestForExport;
import com.taotao.admin.util.ExportExcel;
import com.taotao.rop.database.Constant;
import com.taotao.rop.database.domain.RopAppSecret;
import com.taotao.rop.database.domain.WechatMenu;
import com.taotao.rop.database.domain.WechatRequest;
import com.taotao.rop.database.mapper.RopAppSecretMapper;
import com.taotao.rop.database.mapper.WechatMenuMapper;
import com.taotao.rop.database.mapper.WechatRequestMapper;
import com.taotao.rop.response.BaseResponse;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/wechat/request")
public class WechatRequestController {
    private SimpleDateFormat shortDF = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private WechatRequestMapper requestMapper;
    @Autowired
    private WechatMenuMapper menuMapper;
    @Autowired
    private RopAppSecretMapper appSecretMapper;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Object list(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        Long pageSize = Long.parseLong(request.getParameter("pageSize"));
        Long pageNo = Long.parseLong(request.getParameter("pageNo"));

        String appId = request.getParameter("appId");
        String msgType = request.getParameter("msgType");

        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");

        Long start;
        try {
            Date theStart = shortDF.parse(startDate);
            start = new DateTime(theStart.getTime()).getMillis();
        } catch (Exception e) {
            start = new DateTime(2014, 1, 1, 0, 0).getMillis();
        }
        Long end;
        try {
            Date theEnd = shortDF.parse(endDate);
            end = new DateTime(theEnd.getTime()).plusDays(1).minusMillis(1).getMillis();
        } catch (Exception e) {
            end = DateTime.now().getMillis();
        }

        WechatRequest condition = new WechatRequest();
        condition.setPageSize(pageSize);
        condition.setPageNo(pageNo);
        condition.setStartTime(new Date(start));
        condition.setEndTime(new Date(end));

        if (StringUtils.isNotBlank(msgType) && !"all".equalsIgnoreCase(msgType)) {
            condition.setMsgType(msgType);
        }
        if (StringUtils.isNotBlank(appId) && !MyRopClient.APP_ID.equalsIgnoreCase(appId)) {
            condition.setMsgId(appId);
        }

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(condition, BaseResponse.class, "wechatRequest.list", "1.0");
        if (response.isSuccessful()){
            BaseResponse resp = response.getSuccessResponse();
            if (resp.getSuccess()){
                TableUI tableUI = new TableUI();
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) resp.getData();
                tableUI.setTotal(resp.getMsg());
                tableUI.setRows(respData);
                return tableUI;
            } else {
                return resp;
            }
        } else {
            return response.getErrorResponse();
        }
    }

    @RequestMapping(value = "/exportExcel")
    public String exportExcel(HttpServletRequest request, HttpServletResponse response) {
        String appId = request.getParameter("appId");
        String msgType = request.getParameter("msgType");

        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        Date start;
        try {
            start = shortDF.parse(startDate);
        } catch (Exception e) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(2014, Calendar.JANUARY, 1);
            start = calendar.getTime();
            startDate = "2014-01-01";
        }
        Date end;
        try {
            end = shortDF.parse(endDate);
            end = new Date(end.getTime() + 24 * 3600 * 1000 - 1);
        } catch (Exception e) {
            end = new Date();
            endDate = shortDF.format(end);
        }

        WechatRequest condition = new WechatRequest();
        if (StringUtils.isNotBlank(msgType) && !"all".equalsIgnoreCase(msgType)) {
            condition.setMsgType(msgType);
        }
        if (StringUtils.isNotBlank(appId) && !MyRopClient.APP_ID.equalsIgnoreCase(appId)) {
            condition.setMsgId(appId);
        }
        condition.setStartTime(new Date(start.getTime() + 14 * 3600 * 1000));
        condition.setEndTime(new Date(end.getTime() + 14 * 3600 * 1000));

        response.setContentType("application/binary;charset=ISO8859_1");
        try
        {
            ServletOutputStream outputStream = response.getOutputStream();
            String title = startDate + "到" + endDate + "的请求应答消息记录";
            String encodeTitle = new String(title.getBytes(), "ISO8859_1");
            response.setHeader("Content-disposition", "attachment; filename=" + encodeTitle + ".xls");// 组装附件名称和格式
            String[] headers = {"AppId", "OpenId", "用户类型", "消息类型", "事件", "事件值", "请求消息", "应答消息", "创建时间" };
            List<WechatRequest> data = requestMapper.getList(condition);
            List<WechatRequestForExport> dataset = new ArrayList<WechatRequestForExport>();
            WechatMenu menuCondition = new WechatMenu();
            List<WechatMenu> tempMenu;
            RopAppSecret appCondition = new RopAppSecret();
            List<RopAppSecret> tempApps;
            for (WechatRequest wechatRequest : data) {
                //处理菜单名称的映射
                if (StringUtils.isNotBlank(wechatRequest.getEventkey())) {
                    menuCondition.setKey(wechatRequest.getEventkey());
                    menuCondition.setUrl(wechatRequest.getEventkey());
                    menuCondition.setStatus(Constant.STATUS_ENABLE);
                    menuCondition.setAppId(wechatRequest.getMsgId());
                    tempMenu = menuMapper.getByKeyOrURL(menuCondition);
                    if (tempMenu != null && tempMenu.size() > 0) {
                        wechatRequest.setEventkey(tempMenu.get(0).getName());
                    }
                }
                //处理appId
                if (StringUtils.isNotBlank(wechatRequest.getMsgId())) {
                    appCondition.setAppId(wechatRequest.getMsgId());
                    tempApps = appSecretMapper.getList(appCondition);
                    if (tempApps != null && tempApps.size() > 0) {
                        if (StringUtils.isNotBlank(tempApps.get(0).getDescription())) {
                            wechatRequest.setMsgId(tempApps.get(0).getDescription());
                        }
                    }
                }

                WechatRequestForExport orderForExport = new WechatRequestForExport();
                wechatRequest.copyTo(orderForExport);
                dataset.add(orderForExport);
            }
            new ExportExcel<WechatRequestForExport>().exportExcel(title, headers, dataset, outputStream, "yyyy-MM-dd HH:mm:ss");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
